<template>
  <div class="bg-gray-50 min-h-screen">
    <!-- 页面头部 -->
    <page-header 
      title="关键词监控" 
      subtitle="跟踪和分析网站在搜索引擎中的关键词排名和表现"
    >
      <template #extra>
        <button 
          class="btn btn-primary"
          @click="showAddKeywordDialog = true"
        >
          <i class="fa fa-plus mr-1"></i>添加关键词
        </button>
      </template>
    </page-header>
    
    <!-- 主要内容区 -->
    <div class="px-4 sm:px-6 lg:px-8 py-6">
      <!-- 数据概览卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
        <div class="bg-white rounded-lg shadow p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-gray-500">监控关键词总数</p>
              <h3 class="text-2xl font-bold text-gray-900 mt-1">{{ stats.totalKeywords }}</h3>
            </div>
            <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
              <i class="fa fa-tags text-blue-600"></i>
            </div>
          </div>
          <div class="mt-4 flex items-center text-sm">
            <span class="text-green-600 flex items-center">
              <i class="fa fa-arrow-up mr-1"></i>{{ stats.keywordGrowth }}%
            </span>
            <span class="text-gray-500 ml-2">较上月</span>
          </div>
        </div>
        
        <div class="bg-white rounded-lg shadow p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-gray-500">排名上升关键词</p>
              <h3 class="text-2xl font-bold text-gray-900 mt-1">{{ stats.rankingUp }}</h3>
            </div>
            <div class="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center">
              <i class="fa fa-arrow-up text-green-600"></i>
            </div>
          </div>
          <div class="mt-4 flex items-center text-sm">
            <span class="text-green-600">表现良好</span>
          </div>
        </div>
        
        <div class="bg-white rounded-lg shadow p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-gray-500">排名下降关键词</p>
              <h3 class="text-2xl font-bold text-gray-900 mt-1">{{ stats.rankingDown }}</h3>
            </div>
            <div class="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center">
              <i class="fa fa-arrow-down text-red-600"></i>
            </div>
          </div>
          <div class="mt-4 flex items-center text-sm">
            <span class="text-red-600">需要关注</span>
          </div>
        </div>
        
        <div class="bg-white rounded-lg shadow p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-gray-500">Top 10 关键词</p>
              <h3 class="text-2xl font-bold text-gray-900 mt-1">{{ stats.top10Keywords }}</h3>
            </div>
            <div class="w-10 h-10 rounded-full bg-yellow-100 flex items-center justify-center">
              <i class="fa fa-trophy text-yellow-600"></i>
            </div>
          </div>
          <div class="mt-4 flex items-center text-sm">
            <span class="text-gray-500">占总关键词 {{ stats.top10Percentage }}%</span>
          </div>
        </div>
      </div>
      
      <!-- 搜索和筛选 -->
      <div class="bg-white rounded-lg shadow-md p-4 mb-6">
        <div class="flex flex-col md:flex-row gap-4">
          <div class="flex-1">
            <div class="relative">
              <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
              <input
                type="text"
                v-model="searchKeyword"
                placeholder="搜索关键词..."
                class="form-input pl-10 w-full"
              >
            </div>
          </div>
          <div class="flex gap-4">
            <div class="w-40">
              <select
                v-model="filterEngine"
                class="form-input w-full"
              >
                <option value="all">所有搜索引擎</option>
                <option value="baidu">百度</option>
                <option value="google">Google</option>
                <option value="bing">Bing</option>
                <option value="sogou">搜狗</option>
              </select>
            </div>
            <div class="w-40">
              <select
                v-model="filterStatus"
                class="form-input w-full"
              >
                <option value="all">所有状态</option>
                <option value="up">排名上升</option>
                <option value="down">排名下降</option>
                <option value="stable">排名稳定</option>
              </select>
            </div>
            <div class="w-40">
              <select
                v-model="filterPosition"
                class="form-input w-full"
              >
                <option value="all">所有排名</option>
                <option value="1-10">Top 10</option>
                <option value="11-30">11-30</option>
                <option value="31-50">31-50</option>
                <option value="51+">51+</option>
              </select>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 趋势图表 -->
      <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">关键词排名趋势</h3>
        <div class="h-80">
          <canvas id="rankingTrendChart"></canvas>
        </div>
      </div>
      
      <!-- 关键词列表 -->
      <div class="bg-white rounded-lg shadow-md overflow-hidden">
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  关键词
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  搜索引擎
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  当前排名
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  上周排名
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  变化
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  搜索量
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  难度
                </th>
                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                  操作
                </th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
              <tr v-for="keyword in filteredKeywords" :key="keyword.id" class="hover:bg-gray-50 transition-colors">
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="text-sm font-medium text-gray-900">{{ keyword.text }}</div>
                  <div class="text-xs text-gray-500">{{ keyword.url }}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="flex items-center">
                    <img 
                      :src="getSearchEngineIcon(keyword.engine)" 
                      alt="搜索引擎图标" 
                      class="w-5 h-5 mr-2"
                    >
                    <span class="text-sm text-gray-900">{{ getSearchEngineName(keyword.engine) }}</span>
                  </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800">
                    {{ keyword.currentRank }}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {{ keyword.previousRank }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span 
                    class="text-sm font-medium"
                    :class="keyword.change > 0 ? 'text-green-600' : keyword.change < 0 ? 'text-red-600' : 'text-gray-500'"
                  >
                    <i v-if="keyword.change > 0" class="fa fa-arrow-up mr-1"></i>
                    <i v-if="keyword.change < 0" class="fa fa-arrow-down mr-1"></i>
                    {{ keyword.change !== 0 ? Math.abs(keyword.change) : '-' }}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {{ keyword.searchVolume }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="w-full bg-gray-200 rounded-full h-2">
                    <div 
                      class="h-2 rounded-full"
                      :class="keyword.difficulty <= 30 ? 'bg-green-500' : keyword.difficulty <= 70 ? 'bg-yellow-500' : 'bg-red-500'"
                      :style="{ width: keyword.difficulty + '%' }"
                    ></div>
                  </div>
                  <div class="text-xs text-gray-500 mt-1">{{ keyword.difficulty }}%</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                  <button 
                    class="text-blue-600 hover:text-blue-900 mr-3"
                    @click="handleEditKeyword(keyword)"
                  >
                    编辑
                  </button>
                  <button 
                    class="text-red-600 hover:text-red-900"
                    @click="handleDeleteKeyword(keyword)"
                  >
                    删除
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        
        <!-- 分页 -->
        <div class="px-6 py-4 bg-gray-50 border-t border-gray-200 flex items-center justify-between">
          <div class="flex-1 flex justify-between sm:hidden">
            <button class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
              上一页
            </button>
            <button class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
              下一页
            </button>
          </div>
          <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
            <div>
              <p class="text-sm text-gray-700">
                显示第 <span class="font-medium">{{ (currentPage - 1) * pageSize + 1 }}</span> 到 <span class="font-medium">{{ Math.min(currentPage * pageSize, filteredKeywords.length) }}</span> 条，共 <span class="font-medium">{{ filteredKeywords.length }}</span> 条记录
              </p>
            </div>
            <div>
              <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                <button 
                  class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50"
                  :disabled="currentPage === 1"
                  @click="currentPage = currentPage - 1"
                >
                  <span class="sr-only">上一页</span>
                  <i class="fa fa-chevron-left text-xs"></i>
                </button>
                <button 
                  v-for="page in pageNumbers" 
                  :key="page"
                  class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium"
                  :class="currentPage === page ? 'z-10 bg-primary text-white border-primary' : 'text-gray-700 hover:bg-gray-50'"
                  @click="currentPage = page"
                >
                  {{ page }}
                </button>
                <button 
                  class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50"
                  :disabled="currentPage === totalPages"
                  @click="currentPage = currentPage + 1"
                >
                  <span class="sr-only">下一页</span>
                  <i class="fa fa-chevron-right text-xs"></i>
                </button>
              </nav>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 添加/编辑关键词对话框 -->
    <FormDataEditDialog
      :visible="showAddKeywordDialog || showEditKeywordDialog"
      :formTitle="showEditKeywordDialog ? '编辑关键词' : '添加监控关键词'"
      :formFields="keywordFormFields"
      :initialData="currentKeyword"
      submitText="保存"
      @submit="handleSaveKeyword"
      @cancel="handleCancelKeywordDialog"
    />
    
    <!-- 删除确认对话框 -->
    <ConfirmDialog
      :visible="showDeleteConfirm"
      title="删除关键词"
      message="确定要删除这个监控关键词吗？相关的历史数据也将被删除。"
      confirmText="删除"
      @confirm="confirmDeleteKeyword"
      @cancel="showDeleteConfirm = false"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Chart, registerables } from 'chart.js'
import FormDataEditDialog from '@/components/FormDataEditDialog.vue'
import ConfirmDialog from '@/components/ConfirmDialog.vue'
import { 
  getKeywords, 
  addKeyword, 
  updateKeyword, 
  deleteKeyword, 
  getKeywordStats 
} from '@/api/seo'

// 注册Chart.js组件
Chart.register(...registerables)

// 路由实例
const router = useRouter()

// 状态变量
const stats = ref({
  totalKeywords: 0,
  keywordGrowth: 0,
  rankingUp: 0,
  rankingDown: 0,
  top10Keywords: 0,
  top10Percentage: 0
})

const keywords = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)

// 筛选条件
const searchKeyword = ref('')
const filterEngine = ref('all')
const filterStatus = ref('all')
const filterPosition = ref('all')

// 对话框状态
const showAddKeywordDialog = ref(false)
const showEditKeywordDialog = ref(false)
const showDeleteConfirm = ref(false)
const currentKeyword = ref(null)

// 图表实例
let rankingChart = null

// 关键词表单字段配置
const keywordFormFields = [
  {
    type: 'text',
    name: 'text',
    label: '关键词',
    required: true,
    placeholder: '输入要监控的关键词',
    maxlength: 100
  },
  {
    type: 'url',
    name: 'url',
    label: '目标URL',
    required: true,
    placeholder: 'https://example.com/target-page',
    maxlength: 255
  },
  {
    type: 'select',
    name: 'engine',
    label: '搜索引擎',
    required: true,
    options: [
      { value: 'baidu', label: '百度' },
      { value: 'google', label: 'Google' },
      { value: 'bing', label: 'Bing' },
      { value: 'sogou', label: '搜狗' }
    ]
  },
  {
    type: 'text',
    name: 'notes',
    label: '备注',
    placeholder: '添加关于这个关键词的备注信息（可选）',
    maxlength: 500
  }
]

// 获取搜索引擎名称
const getSearchEngineName = (engine) => {
  const engines = {
    'baidu': '百度',
    'google': 'Google',
    'bing': 'Bing',
    'sogou': '搜狗'
  }
  return engines[engine] || engine
}

// 获取搜索引擎图标（实际项目中应替换为真实图标URL）
const getSearchEngineIcon = (engine) => {
  // 这里使用占位图示例，实际项目中替换为真实图标
  return `https://picsum.photos/20/20?random=${engine}`
}

// 筛选关键词列表
const filteredKeywords = computed(() => {
  return keywords.value.filter(keyword => {
    // 关键词搜索筛选
    if (searchKeyword.value && !keyword.text.toLowerCase().includes(searchKeyword.value.toLowerCase())) {
      return false
    }
    
    // 搜索引擎筛选
    if (filterEngine.value !== 'all' && keyword.engine !== filterEngine.value) {
      return false
    }
    
    // 排名状态筛选
    if (filterStatus.value !== 'all') {
      if (filterStatus.value === 'up' && keyword.change <= 0) return false
      if (filterStatus.value === 'down' && keyword.change >= 0) return false
      if (filterStatus.value === 'stable' && keyword.change !== 0) return false
    }
    
    // 排名位置筛选
    if (filterPosition.value !== 'all') {
      const rank = keyword.currentRank
      if (filterPosition.value === '1-10' && (rank < 1 || rank > 10)) return false
      if (filterPosition.value === '11-30' && (rank < 11 || rank > 30)) return false
      if (filterPosition.value === '31-50' && (rank < 31 || rank > 50)) return false
      if (filterPosition.value === '51+' && rank < 51) return false
    }
    
    return true
  })
})

// 分页处理
const paginatedKeywords = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  return filteredKeywords.value.slice(startIndex, startIndex + pageSize.value)
})

// 总页数
const totalPages = computed(() => {
  return Math.ceil(filteredKeywords.value.length / pageSize.value)
})

// 页码列表（最多显示5个页码）
const pageNumbers = computed(() => {
  const pages = []
  const total = totalPages.value
  
  if (total <= 5) {
    for (let i = 1; i <= total; i++) pages.push(i)
    return pages
  }
  
  if (currentPage.value <= 3) {
    return [1, 2, 3, 4, 5]
  }
  
  if (currentPage.value >= total - 2) {
    return [total - 4, total - 3, total - 2, total - 1, total]
  }
  
  return [
    currentPage.value - 2,
    currentPage.value - 1,
    currentPage.value,
    currentPage.value + 1,
    currentPage.value + 2
  ]
})

// 初始化图表
const initChart = () => {
  const ctx = document.getElementById('rankingTrendChart').getContext('2d')
  
  // 销毁现有图表
  if (rankingChart) {
    rankingChart.destroy()
  }
  
  // 图表数据（实际项目中应从API获取）
  const chartData = {
    labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
    datasets: [
      {
        label: 'Top 10 关键词',
        data: [8, 12, 15, 13, 18, 22],
        borderColor: '#3b82f6',
        backgroundColor: 'rgba(59, 130, 246, 0.1)',
        tension: 0.3,
        fill: true
      },
      {
        label: '平均排名',
        data: [25, 22, 18, 20, 15, 12],
        borderColor: '#10b981',
        backgroundColor: 'transparent',
        tension: 0.3,
        yAxisID: 'y1'
      }
    ]
  }
  
  // 创建图表
  rankingChart = new Chart(ctx, {
    type: 'line',
    data: chartData,
    options: {
      responsive: true,
      maintainAspectRatio: false,
      interaction: {
        mode: 'index',
        intersect: false
      },
      scales: {
        y: {
          beginAtZero: true,
          title: {
            display: true,
            text: '关键词数量'
          }
        },
        y1: {
          position: 'right',
          beginAtZero: true,
          title: {
            display: true,
            text: '平均排名'
          },
          grid: {
            drawOnChartArea: false
          }
        }
      }
    }
  })
}

// 获取关键词数据
const fetchKeywords = async () => {
  try {
    loading.value = true
    const response = await getKeywords()
    keywords.value = response.data || []
  } catch (error) {
    console.error('获取关键词数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const response = await getKeywordStats()
    stats.value = response.data || {
      totalKeywords: 0,
      keywordGrowth: 0,
      rankingUp: 0,
      rankingDown: 0,
      top10Keywords: 0,
      top10Percentage: 0
    }
  } catch (error) {
    console.error('获取关键词统计失败:', error)
  }
}

// 初始化数据
onMounted(async () => {
  await Promise.all([fetchKeywords(), fetchStats()])
  initChart()
})

// 监听筛选条件变化，重置页码
watch([searchKeyword, filterEngine, filterStatus, filterPosition], () => {
  currentPage.value = 1
})

// 编辑关键词
const handleEditKeyword = (keyword) => {
  currentKeyword.value = { ...keyword }
  showEditKeywordDialog.value = true
}

// 删除关键词
const handleDeleteKeyword = (keyword) => {
  currentKeyword.value = keyword
  showDeleteConfirm.value = true
}

// 确认删除关键词
const confirmDeleteKeyword = async () => {
  if (!currentKeyword.value) return
  
  try {
    await deleteKeyword(currentKeyword.value.id)
    fetchKeywords()
    fetchStats()
    showDeleteConfirm.value = false
  } catch (error) {
    console.error('删除关键词失败:', error)
    alert('删除失败: ' + (error.message || '未知错误'))
  }
}

// 保存关键词（新增或编辑）
const handleSaveKeyword = async (data) => {
  try {
    if (showEditKeywordDialog.value) {
      // 编辑现有关键词
      await updateKeyword(currentKeyword.value.id, data)
    } else {
      // 添加新关键词
      await addKeyword(data)
    }
    
    // 刷新数据
    fetchKeywords()
    fetchStats()
    
    // 关闭对话框
    handleCancelKeywordDialog()
  } catch (error) {
    console.error('保存关键词失败:', error)
    throw new Error(error.message || '保存关键词失败，请重试')
  }
}

// 取消关键词对话框
const handleCancelKeywordDialog = () => {
  showAddKeywordDialog.value = false
  showEditKeywordDialog.value = false
  currentKeyword.value = null
}
</script>
